import KoaRouter from 'koa-router'
import { Models } from '@/common/typings/modle'
import { command } from '@/server/mysql'
import { ParameterException, QueryFailed, Success } from '@/core/HttpException'
import Config from '@/config/Config'
import validator from '@/middlewares/validator'
import schema from '@/common/api-json-schema/system/auth/login'
// import verificationCodeValidator from '@/middlewares/verificationCodeValidator'
import { generateToken } from '@/server/auth'
import { Account } from '@/common/typings/account'
import { saveToken } from '@/server/redis'

const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/auth`,
})

router.post('/login', validator(schema, 'body'), async (ctx: Models.Ctx) => {
  const { password, userName } = ctx.request.body as any
  const res: Models.Result = await command(`SELECT * FROM system_user WHERE mobile = '${userName}';`)
  if ((res.results as Account.User[]).length > 0) {
    const user = res.results[0]
    const token = getToken(user, password)
    await saveToken(token, JSON.stringify({ id: user.id, userName: user.userName }))
    throw new Success({ data: token })
  } else {
    throw new QueryFailed({ msg: '用户名或密码错误' })
  }
})
export default router

export function getToken(user: Account.User, password: string): string {
  if (user.password !== password) {
    throw new ParameterException({ msg: '密码不正确' })
  }
  return generateToken(JSON.stringify({ id: user.id, userName: user.userName }), user.roleIds)
}
